package example.fileuplaod2;

import grpc.htsoft.fileupload2.FileChunk;
import grpc.htsoft.fileupload2.FileUploadServiceGrpc;
import grpc.htsoft.fileupload2.UploadStatus;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.io.FileInputStream;
import java.io.IOException;

public class FileUploadClient {
    private final ManagedChannel channel;
    private final FileUploadServiceGrpc.FileUploadServiceStub asyncStub;

    public FileUploadClient(String host, int port) {
        this.channel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build();
        asyncStub = FileUploadServiceGrpc.newStub(channel);
    }

    public void uploadFile(String path) {
        StreamObserver<UploadStatus> responseObserver = new StreamObserver<UploadStatus>() {
            @Override
            public void onNext(UploadStatus value) {
                System.out.println(value.getMessage());
            }

            @Override
            public void onError(Throwable t) {
                t.printStackTrace();
            }

            @Override
            public void onCompleted() {


                System.out.println("File upload completed.");
                channel.shutdownNow();
            }
        };

        StreamObserver<FileChunk> requestObserver = asyncStub.upload(responseObserver);
        try {
            FileInputStream input = new FileInputStream(path);
            byte[] buffer = new byte[4096]; // Adjust the buffer size if needed
            int size;
            while ((size = input.read(buffer)) > 0) {
                FileChunk chunk = FileChunk.newBuilder()
                        .setContent(com.google.protobuf.ByteString.copyFrom(buffer, 0, size))
                        .build();
                requestObserver.onNext(chunk);
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
            requestObserver.onError(e);
            return;
        }
        requestObserver.onCompleted();

        // Wait for the server to shut down (not strictly necessary, but provides cleaner shutdown)
        try {
            channel.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        FileUploadClient client = new FileUploadClient("localhost", 50051);
        client.uploadFile("/Users/zgw/image/0.png");
    }
            }